package com.ruoyi.outcome.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.core.utils.file.FileTypeUtils;
import com.ruoyi.common.core.utils.file.MimeTypeUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.outcome.domain.vo.ResearchOutcomeTrack;
import com.ruoyi.system.api.RemoteFileService;
import com.ruoyi.system.api.RemoteProjectResearchService;
import com.ruoyi.system.api.domain.ProjectResearch;
import com.ruoyi.system.api.domain.SysFile;
import com.ruoyi.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.outcome.domain.ResearchOutcome;
import com.ruoyi.outcome.service.IResearchOutcomeService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 科研项目成果Controller
 * 
 * @author ruoyi
 * @date 2025-01-06
 */
@RestController
@RequestMapping("/outcome")
public class ResearchOutcomeController extends BaseController
{
    @Autowired
    private IResearchOutcomeService researchOutcomeService;

    @Autowired
    private RemoteFileService remoteFileService;

    @Autowired
    private RemoteProjectResearchService remoteProjectResearchService;

    /**
     * 查询科研项目成果列表
     */
    @RequiresPermissions("outcome:outcome:list")
    @GetMapping("/list")
    public TableDataInfo list(ResearchOutcome researchOutcome)
    {
        startPage();
        researchOutcome.setIsDeleted(0);
        List<ResearchOutcome> list = researchOutcomeService.selectResearchOutcomeList(researchOutcome);
//        for(ResearchOutcome outcome:list)
//        {
//            R<ProjectResearch> pr= remoteProjectResearchService.getProjectInfo(outcome.getProjectId());
//            ProjectResearch projectResearch = pr.getData();
//            if (projectResearch != null)
//            {
//                outcome.setProjectName(projectResearch.getProjectName());
//            }
//        }
        return getDataTable(list);
    }

    /**
     * 导出科研项目成果列表
     */
    @RequiresPermissions("outcome:outcome:export")
    @Log(title = "科研项目成果", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ResearchOutcome researchOutcome)
    {
        List<ResearchOutcome> list = researchOutcomeService.selectResearchOutcomeList(researchOutcome);
        ExcelUtil<ResearchOutcome> util = new ExcelUtil<ResearchOutcome>(ResearchOutcome.class);
        util.exportExcel(response, list, "科研项目成果数据");
    }

    /**
     * 获取科研项目成果详细信息
     */
    @RequiresPermissions("outcome:outcome:query")
    @GetMapping(value = "/{outcomeId}")
    public AjaxResult getInfo(@PathVariable("outcomeId") Long outcomeId)
    {
        return success(researchOutcomeService.selectResearchOutcomeByOutcomeId(outcomeId));
    }

    /**
     * 新增科研项目成果
     */
    @RequiresPermissions("outcome:outcome:add")
    @Log(title = "科研项目成果", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ResearchOutcome researchOutcome)
    {
        // 获取当前用户信息
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        researchOutcome.setCreatedBy(sysUser.getUserName());
        researchOutcomeService.insertResearchOutcome(researchOutcome);
        // 添加追踪记录
        ResearchOutcomeTrack outcomeTrack = new ResearchOutcomeTrack();
        BeanUtils.copyProperties(researchOutcome, outcomeTrack);
        outcomeTrack.setActionType("ADD");
        researchOutcomeService.insertResearchOutcomeAudit(outcomeTrack);
        return success();
        //return toAjax(researchOutcomeService.insertResearchOutcome(researchOutcome));
    }

    /**
     * 修改科研项目成果
     */
    @RequiresPermissions("outcome:outcome:edit")
    @Log(title = "科研项目成果", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ResearchOutcome researchOutcome)
    {
        SysUser sysUser = SecurityUtils.getLoginUser().getSysUser();
        researchOutcome.setUpdatedBy(sysUser.getUserName());
        researchOutcome.setUpdatedAt(new Date());
        researchOutcomeService.updateResearchOutcome(researchOutcome);

        ResearchOutcomeTrack outcomeTrack = new ResearchOutcomeTrack();
        BeanUtils.copyProperties(researchOutcome, outcomeTrack);
        outcomeTrack.setActionType("UPDATE");
        researchOutcomeService.insertResearchOutcomeAudit(outcomeTrack);
        return success();
       // return toAjax(researchOutcomeService.updateResearchOutcome(researchOutcome));
    }

    /**
     * 删除科研项目成果
     */
    @RequiresPermissions("outcome:outcome:remove")
    @Log(title = "科研项目成果", businessType = BusinessType.DELETE)
	@DeleteMapping("/{outcomeIds}")
    public AjaxResult remove(@PathVariable Long[] outcomeIds)
    {

       for(Long outcomeId:outcomeIds)
      {
            ResearchOutcome researchOutcome = researchOutcomeService.selectResearchOutcomeByOutcomeId(outcomeId);
            researchOutcome.setIsDeleted(1);
            researchOutcome.setDeletedBy(SecurityUtils.getUsername());
            researchOutcome.setDeletedAt(new Date());
            researchOutcomeService.updateResearchOutcome(researchOutcome);
            //添加追踪记录
            ResearchOutcomeTrack outcomeTrack = new ResearchOutcomeTrack();
            BeanUtils.copyProperties(researchOutcome, outcomeTrack);
            outcomeTrack.setActionType("DELETE");
            researchOutcomeService.insertResearchOutcomeAudit(outcomeTrack);
  }
       return success();
       //return toAjax(researchOutcomeService.deleteResearchOutcomeByOutcomeIds(outcomeIds));
    }

    /**
     * 图片上传
     */
    @Log(title = "用户头像", businessType = BusinessType.INSERT)
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file)
    {
        if (!file.isEmpty())
        {
            String extension = FileTypeUtils.getExtension(file);
            if (!StringUtils.equalsAnyIgnoreCase(extension, MimeTypeUtils.IMAGE_EXTENSION))
            {
                return error("文件格式不正确，请上传" + Arrays.toString(MimeTypeUtils.IMAGE_EXTENSION) + "格式");
            }
            R<SysFile> fileResult = remoteFileService.upload(file);
            if (StringUtils.isNull(fileResult) || StringUtils.isNull(fileResult.getData()))
            {
                return error("文件服务异常，请联系管理员");
            }

            String url = fileResult.getData().getUrl();
            AjaxResult ajax = AjaxResult.success();
            ajax.put("imgUrl", url);
            return ajax;
        }
        return error("上传图片异常，请联系管理员");
    }


    @GetMapping(value = "/outcometrack/{outcomeId}")
    public AjaxResult getauditInfo(@PathVariable("outcomeId") Long outcomeId)
    {
        List<ResearchOutcomeTrack> list =researchOutcomeService.selectResearchOutcomeAuditList(outcomeId);
        return AjaxResult.success(list);
    }

}
